package yourobot.bonus;

import java.awt.Color;
import java.util.Random;

import org.jbox2d.callbacks.QueryCallback;
import org.jbox2d.collision.AABB;
import org.jbox2d.common.Vec2;
import org.jbox2d.dynamics.BodyType;
import org.jbox2d.dynamics.Fixture;
import org.jbox2d.dynamics.World;

import yourobot.Wall;
import yourobot.Wall.WallType;
import yourobot.config.WallColorConfig;
import yourobot.robots.Player;
/**
 * 
 * @author mehdimasrour
 *
 */
public class Bomb implements Bonus {

	public static enum BombType{
		WOOD, STONE, ICE
	};
	
	private static final int MAX_X = 750;
	private static final int MAX_Y = 550;
	
	private WallType type;
	private final int x;
	private final int y;
	
	public Bomb(){
		Random r = new Random(System.nanoTime());
		x = r.nextInt(MAX_X);
		y = r.nextInt(MAX_Y);
		switch (r.nextInt(3)){
		
			case 0:
				type=WallType.WOOD;
				break;
			
			case 1:
				type=WallType.STONE;
				break;
			
			case 2:
				type=WallType.ICE;
				break;
		}
		
	}
	
	@Override
	public Vec2 getPosition(){
		return new Vec2(x,y);
	}
	
	/**
	 * 
	 * @return The WallType associated with the Bomb, bomb has more effect when used on a wall of the same type
	 */
	public WallType getWallType(){
		return type;
	}
	
	@Override
	public void useBonus(World w, final Player p) {
		AABB aabb = new AABB(new Vec2(p.getPosition().x-100, p.getPosition().y-100), new Vec2(p.getPosition().x+100, p.getPosition().y+100));
		w.queryAABB(new QueryCallback() {
			
			@Override
			public boolean reportFixture(Fixture fixture) {
				if ( fixture.getUserData().equals("wall1") ){
					Wall w = (Wall)fixture.getBody().getUserData();
					int power;
					if (w.getType() == getWallType() ) power = 2000;
					else power = 50;
					double angle = Math.atan2(fixture.getBody().getPosition().y-p.getPosition().y, fixture.getBody().getPosition().x-p.getPosition().x);
					fixture.getBody().setType(BodyType.DYNAMIC);
					fixture.getBody().setLinearVelocity(new Vec2(power*(float)Math.cos(angle), power*(float)Math.sin(angle)));
				}
				return true;
			}
		}, aabb);
	}

	@Override
	public BonusType getType() {
		return BonusType.BOMB;
	}

	@Override
	public Color getColor() {
		return new WallColorConfig(getWallType()).getColor();
	}

}
